//
//  StringPickerCellData.m
//  18Birdies
//
//  Created by CC on 2017/5/27.
//  Copyright © 2017年 Lc. All rights reserved.
//

#import "StringPickerCellData.h"
#import "LcFoundation.h"
#import "NumberPickerCell.h"

@implementation StringPickerCellData
+ (StringPickerCellData*)cellDataWithValues:(NSArray<NSString*>*)values
                                      value:(int)value {
  LC_CHECK_NOT_EMPTY(values);
  LC_CHECK_TRUE(value < values.count && value >= 0);
  StringPickerCellData* cellData = [[self alloc] init];
  cellData.values = values;
  cellData.value = value;
  cellData.clickable = NO;
  cellData.cellHeight = 162;
  return cellData;
}

- (Class)cellClazz {
  return NumberPickerCell.class;
}

- (NSString*)nibName {
  return @"NumberPickerCell";
}

- (void)refreshCell:(NumberPickerCell*)cell {
  [super refreshCell:cell];
  if (self.hidden) {
    return;
  }
  cell.pickerView.dataSource = self;
  cell.pickerView.delegate = self;
  [cell.pickerView selectRow:[self indexOfCurrentValue]
                 inComponent:0
                    animated:NO];
  [cell.pickerView reloadAllComponents];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView {
  return 1;
}

- (NSInteger)pickerView:(UIPickerView*)pickerView
numberOfRowsInComponent:(NSInteger)component {
  return self.values.count;
}

- (NSString*)pickerView:(UIPickerView*)pickerView
            titleForRow:(NSInteger)row
           forComponent:(NSInteger)component {
  NSString* valueString = self.values[row];
  if (valueString.length == 0) {
    return @"关闭";
  } else {
    return valueString;
  }
}

- (void)pickerView:(UIPickerView*)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {
  self.value = (int)row;
  if ([self.delegate respondsToSelector:@selector(onStringChanged:cellData:)]) {
    [self.delegate onStringChanged:self.value cellData:self];
  }
}

- (int)clampValue:(int)value {
  LC_CHECK_NOT_EMPTY(self.values);
  if (value < self.values.count && value >= 0) {
    return value;
  }
  LC_FAIL();
  return 0;
}

- (void)setValue:(int)value {
  if (self.values.count > 0) {
    value = [self clampValue:value];
  }
  _value = value;
}

- (int)indexOfCurrentValue {
  if (self.value < self.values.count && self.value >= 0) {
    return self.value;
  }
  LC_FAIL();
  return 0;
}
@end
